<template>
	<div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts"; //引入echarts5
// import Echarts from 'echarts' //引入echarts4
// import "echarts-gl"; //引入echarts-gl，3D地图插件
// import "echarts-liquidfill"; // 水球插件
import { graphic } from "echarts"; //引入graphic
require("echarts/theme/macarons"); // echarts主题
import resize from "./mixins/resize"; //重绘图表函数并自适应
export default {
	name: "Echart",
	mixins: [resize],
	props: {
		// class名
		className: {
			type: String,
			default: "chart",
		},
		// id，自定义 且必须唯一，不能重复
		id: {
			type: String,
			default: "chart",
		},
		// 图表宽度
		width: {
			type: String,
			default: "100%",
		},
		// 图标高度
		height: {
			type: String,
			default: "100%",
		},
		// 传入的数据
		options: {
			type: Object,
			// required: true,
			default: () => ({}),
		},
	},
	data() {
		return {
			chart: null, //chart实列
		};
	},
	//监听图表数据时候变化，重新渲染图表
	watch: {
		options: {
			handler(val) {
				// 存在chart时，对chart重绘
				if (this.chart) {
					this.chart.setOption(val, true);
				}
			},
			deep: true,
		},
	},
	mounted() {
		// 初始化chart
		this.$nextTick(() => {
			this.initChart();
		});
	},
	//页面销毁前，销毁事件和实例
	beforeDestroy() {
		if (!this.chart) {
			return;
		}
		this.chart.dispose();
		this.chart = null;
	},
	methods: {
		/**
		 * @description 初始化chart
		 */
		initChart() {
			if (this.chart) {
				this.chart.dispose();
			}
			this.$nextTick(() => {
				setTimeout(() => {
					//使用 macarons 主题
					//配置为 svg 形式，预防页面缩放而出现模糊问题；图表过于复杂时建议使用 Canvas
					this.chart = echarts.init(this.$el, "macarons", { renderer: "svg" });
					this.chart.setOption(this.options, true);
				}, 200);
			});
		},
	},
};
</script>

<style></style>
